﻿$(document).ready(function () {
    //HTML template for a promoter
    var constitutive_markup = "<li id='${id}' class=\"${odd}\"><div class=\"promoter_element\" ><label>Type:</label><b>${ptype}</b><input type=\"hidden\" name=\"ptype\" value=\"${ptype}\" readonly=\"readonly\"/><label>Expression:</label><input type=\"text\" name=\"pexpr\" value=\"${expr}\" /><input type=\"hidden\" name=\"pfactor\" value=\"undefined\"/><input type=\"hidden\" name=\"pexpr1\" value=\"undefined\"/><input type=\"hidden\" name=\"pexpr2\" value=\"undefined\"/><a href=\"javascript:void(0);\" class=\"del\" id=\"${del_id}\" ></a></div></li>";
    var non_constitutive_markup = "<li id='${id}' class=\"${odd}\"><div class=\"promoter_element\" ><label>Type:</label><b>${ptype}</b><input type=\"hidden\" name=\"ptype\" value=\"${ptype}\" readonly=\"readonly\"/><label>Factor:</label><select name=\"pfactor\"></select><label>Expression 1:</label><input type=\"text\" name=\"pexpr1\" value=\"${expr1}\" /><label>Expression 2:</label><input type=\"text\" name=\"pexpr2\" value=\"${expr2}\" /><input type=\"hidden\" name=\"pexpr\" value=\"undefined\"/><a href=\"javascript:void(0);\" class=\"del\" id=\"${del_id}\"></a></div></li>";
    /* Compile markup string as a named template */
    $.template("constitutiveTemplate", constitutive_markup);
    $.template("nonConstitutiveTemplate", non_constitutive_markup);


    function initilize(){
        //Reset all to default value
        $('#type').children('select').val('select');
        $('#expr').children('input').val('');
        $('#expr1').children('input').val('');
        $('#expr2').children('input').val('');
        $('#factor').children('select').val('select');
        //hide further steps
        $('#expr').hide();
        $('#factor').hide();
        $('#expr1').hide();
        $('#expr2').hide();
        $('#ok').attr("disabled", true);
    };
    $("#addPromoter").fancybox({
        'titlePosition' : 'inside',
        'transitionIn'	: 'none',
        'transitionOut'	: 'none',
        'overlayColor'		: '#000',
        'overlayOpacity'	: 0.8,
        'onComplete'    : function(){
            initilize();

        }
    });

    $("#type").children('select').change(function () {
        var type = $("#type").children('select').val();
        switch (type) {
            case "constitutive":
                $('#expr').show();
                $('#factor').hide();
                $('#expr1').hide();
                $('#expr2').hide();
                $('#ok').attr("disabled", false);
                break;
            case "activate":
                $('#expr').hide();
                $('#factor').show();
                $('#expr1').show();
                $('#expr2').show();
                $('#ok').attr("disabled", false);
                break;
            case "repress":
                $('#expr').hide();
                $('#factor').show();
                $('#expr1').show();
                $('#expr2').show();
                $('#ok').attr("disabled", false);
                break;
        }
    });

    function addPromoter(){
        var no_items = $("#promoter_list").children('li').length;
        if (no_items > 0) {
            var last_id = $("#promoter_list").children("li")[no_items - 1].id;
            var new_id = "pro" + (parseInt(last_id.substr(3)) + 1).toString();
            var odd = "";
        } else {
            new_id = "pro1";
        }

        var del_id = "del_" + new_id;
        if (no_items % 2 != 1) {
            odd = "odd";
        }

        var ptype = ($("#type").children('select').val());
        if (ptype == "select") {
            alert("Please select type of the promoter.");
        }
        else if (ptype == "constitutive") {
            var pexpr = $.trim(($("#expr").children('input').val()));
            var new_promoter = {
                odd: odd,
                id: new_id,
                ptype: ptype,
                expr: pexpr,
                del_id: del_id
            }
            $.tmpl("constitutiveTemplate", new_promoter).appendTo("#promoter_list");
        }
        else {
            var pexpr1 = $.trim(($("#expr1").children('input').val()));
            var pexpr2 = $.trim(($("#expr2").children('input').val()));
            var factor = $("#factor").find('select').html();
            var selected = $("#factor").find('select').val();
            new_promoter = {
                odd: odd,
                id: new_id,
                ptype: ptype,
                expr1: pexpr1,
                expr2: pexpr2,
                del_id: del_id
            }
            $.tmpl("nonConstitutiveTemplate", new_promoter).appendTo("#promoter_list");
            $("#" + new_id).find('select').html(factor);
            $("#" + new_id).find('select').val(selected);
        }
    };


    $("#ok").click(function () {
        addPromoter();
        $.fancybox.close();
    });

    $("#next").click(function (){
       addPromoter();
       initilize();
    });

    $("#cancel").click(function () {
        $.fancybox.close();
    });

    $(".del").live('click', function () {
        var item_id = $(this).attr('id').substr(4);
        $("#" + item_id).remove();
        updatePromoterList();
    });

    function updatePromoterList(){
        var items = $("#promoter_list").children('li');
        var no_items = items.length;
        items.each(function(i, item){
            var pos = i+1;
            var new_id = "pro" + (pos).toString();
            var del_id = "del_" + new_id;
            var odd="even";
            if(pos %2 ==1){
                odd="odd"
            }
            $(item).attr('id',new_id);
            $(item).removeClass();
            $(item).addClass(odd);
            $(item).find(".del").attr('id', del_id);
        });
    };
    
    //Storing initial factor concentration data set confirmation
    $("#data_set_name").hide();
    $("#store_data input").click(function (){
        if($("#store_data input").is(":checked")){
            $("#data_set_name").toggle();
        } else {
            $("#data_set_name").hide();
        }
    });
    //Choose datasets
    //alert($("#generate").attr("disabled"))
    //$("#generate").attr("disabled", true);
    $("input[name='generator']").click(function(){
        $("#generate").attr("href", "#");
    })
    $("#generate").click( function (){
        var generator = $("input[name='generator']:checked").val();
        if (generator=="default") {
            $("#initial_stage ul li input").val(0);
        } else if (generator=="random"){
            var min = parseInt($("#min").val());
            var max = parseInt($("#max").val());

            var c_range = max-min;
            if (c_range <=0){
                alert("Minimun value and maximun value are invalid. Please set again.");
                $("#min").focus();
            } else {

                var f_list = $("#initial_stage ul li");

                f_list.each(function(i, f){

                    var random_number = min + Math.random()*c_range;
                    //alert(random_number);
                    $(f).find("input").val(random_number);
                });
            }
        } else if (generator=="userdefined") {
            var url = $("#data_set_chooser option:selected").val();
            if (url=="undefined"){
                alert("Please select a pre-defined dataset.");
                $("#data_set_chooser").focus();
            } else {
                $.get(
                    url,
                    {},
                    function(data){
                        if (data.status == "success"){
                            for (var f in data.data){
                                $("#"+f).val(data.data[f]);
                            }
                        } else {
                            $("#messages").html("<li class=\"error\">"+ data.msg +"<\li>");
                        }
                    },
                    "json"
                    );
            }
        }
    });

    $("#create_ts_instances").submit(function (){
        var valid=true;

        var timestep= $("input[name='timestep']").val();
        if (! /^[0-9]+$/.test(timestep)){
            alert("Number of timesteps is invalid.");
            $("input[name='timestep']").addClass("input-error");
            $("input[name='timestep']").focus();
            valid = false;
            return false;
        };
        var f_list = $("#initial_stage ul li input");

        f_list.each(function(i, f){
            var fc = $(f).val();
            if (! /^(\+?((([0-9]+(\.)?)|([0-9]*\.[0-9]+))([eE][+-]?[0-9]+)?))$/.test(fc)) {
                alert("Initial expression level is invalid.");
                $(f).addClass("input-error");
                $(f).focus();
                valid = false;
            };
            if(valid == false){
                return false;
            }
        });
        return valid;
    });

    /*Javascipt for open fancybox displaying images */
    $("a.thumbnail").fancybox({
        'transitionIn'	:	'elastic',
        'transitionOut'	:	'elastic',
        'speedIn'		:	200,
        'speedOut'		:	200,
        'overlayColor'		: '#000',
        'overlayOpacity'	: 0.8
    });
});
